// Class Player :
function Player(code){
	this.name = 'Player';
	if(typeof code == "undefined"){
		this.race = getRandomInt(0, 7);	// Start with a random race
		this.level = 0;					// Start at level 0 (currently unused)
		this.nbLevelUp = 0;				// Used for Healing potion
		this.gold = 0;					// Start with an empty purse
		this.position = 0;				// Start at the entrance (currently unused)
		this.items = [];				// Start with nothing
		this.nbMaxOfItems = 4;			// Start with 4 inventory slot
		this.raceSensible = true;		// Player can be insensible to racial bonus using nipple clamps
		this.assfuckSensitive = true;	// Player can be insensible to ass fuck using buttplug armor (curently unused)
		this.facefuckSensitive = true;	// Player can be insensible to face fuck using gag armor (currently unused)
	}
	
	// Display the name instead of [object] (currently unused)
	this.toString = function(){
		return this.name;
	};
	
	// Update player with a level up
	this.levelUp = function(){
		this.level += 1;
		this.nbLevelUp += 1;
		this.gold += 1;
	};
	
	// Adding gold to the inventory
	// - Default parameter (no parameters) add 1 gold in the purse (for example usage on default params)
	// - Can be used with negative value to spend gold.
	this.addGold = function(amount){
		if(typeof amount == "undefined"){	// Making empty parameters be handled as '1'
			amount = 1; 
		}
		this.gold += amount;
	};
	
	// Find position of an item in the inventory
	// - In order to simplify, we'll work with an always-sorted-by-Id tab
	this.findPosition = function(item){
		var pos = 0;
		while(pos<this.items.length && this.items[pos]<item.id){
			pos++;
		}
		return pos;
	};

	// Drop an item of the backpack
	this.destroyItem = function(item){
		var pos = this.findPosition(item);
		var tmpTab1 = this.items.slice(0,pos);
		var tmpTab2 = this.items.slice(pos+1,this.items.length);
		this.items = tmpTab1.concat(tmpTab2);
	};
	
	// Add an item in the backpack (always sorted by Id)
	this.addItem = function(item){
		if(this.items.length==0){	// Backpack empty
			this.items.push(item);	
		} 
		else{	// Backpack not empty : adding the item to the correct position
			var cut = this.findPosition(item);
			var tmpTab1 = this.items.slice(0,cut);
			var tmpTab2 = this.items.slice(cut,this.items.length);
			tmpTab1.push(item);
			this.items = tmpTab1.concat(tmpTab2);
		}
	};

	// Buy an item if its enough space in backpack and enough gold in purse
	// - return true if operation success (false otherwise)
	this.buyItem = function(item){
		if(this.items.length < this.nbMaxOfItems && this.gold >= item.price){
			this.addGold(-item.price);	// Update purse
			this.addItem(item);
			return true;
		}
		else{
			return false;
		}
	};
	
	// Sell an item (update the player purse and backpack))
	this.sellItem = function(item){
		WebPlayer.addGold(Math.floor(item.price/2));
		this.detroyItem(item);
	};
	
	// Move the player
	this.changePosition = function(newField){
		this.position = MapFields[this.position].getRealPath(newField);
	};
	
	// Load a saved game
	this.loadGame = function(loadLink)
	{
		if(loadLink != null && loadLink != "")
		{
			var correctPattern = true;
			// validate link
			var gameLinkParams = loadLink.split(":");
			// validate params
			// validate amount of params
			if (gameLinkParams.length != 5)
			{
				FinishLoading(false, "A wrong amount of parameters was given.");
			}
			else
			{
				// prepare items
				var tempItems = gameLinkParams[4].substring(1, gameLinkParams[4].length - 2).split("|");
				var finalItemsKey = new Array();
				var finalItemsValue = new Array();
				for (var index = 0; index < tempItems.length; index++)
				{
					var item = tempItems[index].split("@");
					if (item.length === 2)
					{
						finalItemsKey[index] = parseInt(item[0]);
						finalItemsValue[index] = parseBool(item[1]);
					}
				}
				// put prams into array
				this.race = parseInt(gameLinkParams[0].substring(1));									// race
				this.level = parseInt(gameLinkParams[1]);												// level
				this.gold = parseInt(gameLinkParams[2]);												// gold pieces
				this.position = parseInt(gameLinkParams[3]);											// position
				
				// further validation
				if (isNumber(this.race)
					&& this.race >= 0
					&& this.race <= 7) // validate race
				{
					if (isNumber(this.level)
						&& this.level >= 1) // validate level //why 1 ?
					{
						if (isNumber(this.gold)
							&& this.gold >= 0) // validate gold pieces
						{
							if (isNumber(this.position)
								&& this.position >= 0
								&& this.position <= 11) // validate position
							{
								// validate items
								var invalidItem = false;
								for (var i = 0; i < finalItemsKey.length; i++)
								{
									if (isNaN(finalItemsKey[i])
										   || finalItemsKey[i] < 0
										   || finalItemsKey[i] > 9)
									{
										invalidItem = true;
										break;
									}
								}
								if (invalidItem == false)
								{
									// Updating the items as objects
									this.items.clear();					// Emptying current inventory
									var invalidItemStates = false;
									for (var i = 0; i < finalItemsKey.length; i++)
									{
										var item = ExistingItems[item[0]];
										this.addItem(item);					//adding
										var pos = this.findPosition(item);
										if( ! this.items[pos].update(item[1]) )
										{
											invalidItemStates = true;
											break;
										}
									}
									if (invalidItemStates == false)
									{
										return "Success";
									}
									else
									{
										return "An entered item has an invalid state.";
									}
								}
								else
								{
									return "An entered item was invalid.";	
								}
							}
							else
							{
								return "The entered position was invalid.";						
							}
						}
						else
						{
							return "The entered amount of gold pieces was invalid.";
						}
					}
					else 
					{
						return "The entered level was invalid.";
					}
				}
				else
				{
					return "The entered race was invalid.";
				}
			}
		}
		else
		{
			return "The loading link was empty.";
		}
	};
	
	// Update game link
	this.updateGameLink = function()
	{
		gameLink = "[" + this.race + ":" + this.level + ":" + this.gold + ":" + this.position + ":[";
		for (var i = 0; i < this.items.length; i++)
		{
			gameLink = gameLink + this.items[i].id + "@" + this.items[i].getState();
			if (i != (this.items.length - 1))
			{
				gameLink = gameLink + "|";
			}
		}
		gameLink = gameLink + "]]";
	}
}


// Creates random parameters for a new game - w/o loading
function NewGame()
{
	WebPlayer = new Player();
	StartGame();
}

// Load Game
function LoadGame(loadLink)
{
	if(!gameRunning){
		WebPlayer = new Player();
	}
	var error = WebPlayer.loadGame(loadLink);
	if (error === "Success"){
		StartGame();
	}
	else{
		alert("Game link was not correct: " + message);
	}
}

// Start the game
function StartGame()
{
	MoveMenuBar("left");
	// Correct menu bar display
	$("#saveGameButton").removeClass('disabled');
	$("#newGameButton").addClass('disabled');
	$("#newGameButton").removeClass('buttonHover');
	$("#loadGameButton").addClass('disabled');
	$("#loadGameButton").removeClass('buttonHover');
	$("#gameActionsBar").css({"position" : "absolute", "display" : "block", "left" : "20px", "margin" : "0", "top" : "270px"});
	$("#manualPannel").css("display", "none");
	treasureState[0] = true;
	treasureState[1] = true;
	UpdateRace();
	UpdatePosition();
	UpdateGoldPieces();
	UpdateLevel();
	gameRunning = true;
	WebPlayer.updateGameLink();
	ShowCurrentPosition();
	ShowReachablePositions();
	$("#gamePannel").css("display", "block");
}

